import { Menu } from "antd";
import styled from "@emotion/styled";
import MenuTop from "./menu-top";
import { useRecoilState } from "recoil";
import { userState } from "../../stores/user";
import { useEffect, useState, memo } from "react";
import { RouteVO } from "../../service/rbac/menu-service";
import { ItemType, MenuItemType } from "antd/es/menu/hooks/useItems";
import SvgIcon from "../svgIcon";
import { naviState } from "../../stores/navi";
import { SelectInfo } from "rc-menu/lib/interface";
import { useNavigate } from "react-router";
/**
 * 自定义侧边栏
 */
const MenuBar = () => {
  const [user] = useRecoilState(userState);
  const [items, setItems] = useState<ItemType<MenuItemType>[]>([]);
  const [navi, setNavi] = useRecoilState(naviState);
  const navigate = useNavigate();
  /**
   * 设置路由
   */
  useEffect(() => {
    if (user.route) {
      setItems(getMenuList(user.route));
    }
  }, [user]);

  /**
   * menu 选择的active
   * @param selectedKeys 选中的keys
   */
  const onSelect = ({ keyPath, selectedKeys }: SelectInfo) => {
    //将导航选择的key设置到缓存,以保证刷新时保持原状态
    sessionStorage.setItem(
      "__BEEFSOLVE_BACKWEB__NAVI__",
      JSON.stringify({
        ...navi,
        defaultOpenKeys: keyPath,
        defaultSelectedKeys: [selectedKeys],
      })
    );
    const routes = user.route?.filter((e) => e.id + "" === selectedKeys[0]);
    if (routes && routes.length > 0) {
      //跳转路由
      navigate({ pathname: routes[0].path });
      //获取到点击的menu
      let i = 0;
      let his = null;
      navi.tabHistory.forEach((history, index) => {
        if (history.title === routes[0].meta.title) {
          his = history;
          i = index;
          return;
        }
      });
      if (his) {
        //已存在的tab 选中即可
        const naviData = {
          ...navi,
          defaultOpenKeys: keyPath,
          defaultSelectedKeys: selectedKeys,
          tabActiveIndex: i,
        };
        setNavi(naviData);
        sessionStorage.setItem(
          "__BEEFSOLVE_BACKWEB__NAVI__",
          JSON.stringify(naviData)
        );
      } else {
        //不存在的就增加一个tab,并选中
        const naviData = {
          ...navi,
          defaultOpenKeys: keyPath,
          defaultSelectedKeys: selectedKeys,
          tabHistory: [
            ...navi.tabHistory,
            {
              title: routes[0].meta.title,
              path: routes[0].path,
              key: selectedKeys,
            },
          ],
          tabActiveIndex: navi.tabHistory.length,
        };
        setNavi(naviData);
        sessionStorage.setItem(
          "__BEEFSOLVE_BACKWEB__NAVI__",
          JSON.stringify(naviData)
        );
      }
    }
  };

  const onOpenChange = (openKeys: string[]) => {
    //将导航选择的key设置到缓存,以保证刷新时保持原状态
    const openkeysEnd: string[] =
      openKeys.length > 0 ? [openKeys[openKeys.length - 1]] : [];
    sessionStorage.setItem(
      "__BEEFSOLVE_BACKWEB__NAVI__",
      JSON.stringify({
        ...navi,
        defaultOpenKeys: openkeysEnd,
      })
    );
    setNavi({
      ...navi,
      defaultOpenKeys: openkeysEnd,
    });
  };

  /**
   * 动态递归组装到用户的路由items结构
   * @param route 用户路由
   */

  const getMenuList = (
    routes: RouteVO[],
    parentIndex: number = 0
  ): ItemType<MenuItemType>[] => {
    const items: ItemType<MenuItemType>[] = [];
    routes.forEach((route) => {
      if (route.parentId === parentIndex) {
        const children = getMenuList(routes, route.id);
        items.push({
          label: route.meta.title,
          key: route.id,
          icon: route.meta.icon ? (
            <span className="anticon anticon-pie-chart ant-menu-item-icon">
              <SvgIcon name={route.meta.icon} size={18} color="#f5f5f5" />
            </span>
          ) : undefined,
          children: children.length > 0 ? children : undefined,
        });
      }
    });
    return items;
  };

  return (
    <MenuBarContainer>
      <MenuTop />
      <Menu
        items={items}
        mode="inline"
        inlineCollapsed={navi.defaultOpenStatus}
        defaultOpenKeys={navi.defaultOpenKeys}
        openKeys={navi.defaultOpenKeys}
        selectedKeys={navi.defaultSelectedKeys}
        onSelect={onSelect}
        onOpenChange={onOpenChange}
      />
    </MenuBarContainer>
  );
};

export default memo(MenuBar);

const MenuBarContainer = styled.div``;
